﻿using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Web;

namespace QBS.Tools
{
    public static class Crypt
    {
        private static string BinToStr(byte[] buf)
        {
            string ret = string.Empty;
            foreach (byte by in buf)
            {
                string tmp = String.Format("{0:X}", by);
                if (tmp.Length == 1)
                    tmp = "0" + tmp;
                ret += tmp;
            }
            return ret;
        }
        private static byte[] StrToBin(string buf)
        {
            int len = buf.Length / 2;
            byte[] ret = new byte[len];
            for (int i = 0; i < len; i++)
            {
                string tmp = (buf[i * 2] + "" + buf[i * 2 + 1]);

                ret[i] = Convert.ToByte(tmp, 16);
            }
            return ret;
        }
        #region AES
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="toEncrypt">要加密的内容</param>
        /// <param name="strKey">密钥（16或者32位）</param>
        /// <returns>Base64转码后的密文</returns>
        public static string Encrypt(string toEncrypt, string strKey, bool base64 = true)
        {
            if (strKey.Length > 16)
                strKey = strKey.Substring(0, 16);
            byte[] tmp = Encoding.Default.GetBytes(strKey);
            byte[] keyArray = new byte[16];
            tmp.CopyTo(keyArray, 0);
            byte[] toEncryptArray = Encoding.Default.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();//using System.Security.Cryptography;    
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;//using System.Security.Cryptography;    
            rDel.Padding = PaddingMode.Zeros;//using System.Security.Cryptography;   

            ICryptoTransform cTransform = rDel.CreateEncryptor();//using System.Security.Cryptography;    
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return base64 ? Convert.ToBase64String(resultArray, 0, resultArray.Length) : BinToStr(resultArray);
        }
        public static string Encrypt(byte[] toEncryptArray, string strKey, bool base64 = true)
        {
            if (strKey.Length > 16)
                strKey = strKey.Substring(0, 16);
            byte[] tmp = Encoding.Default.GetBytes(strKey);
            byte[] keyArray = new byte[16];

            tmp.CopyTo(keyArray, 0);

            RijndaelManaged rDel = new RijndaelManaged();//using System.Security.Cryptography;    
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;//using System.Security.Cryptography;    
            rDel.Padding = PaddingMode.Zeros;//using System.Security.Cryptography;   

            ICryptoTransform cTransform = rDel.CreateEncryptor();//using System.Security.Cryptography;    
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return base64 ? Convert.ToBase64String(resultArray, 0, resultArray.Length) : BinToStr(resultArray);
        }
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="toDecrypt">要解密的内容</param>
        /// <param name="strKey">密钥（16或者32位）</param>
        /// <returns>解密后的明文</returns>
        public static string Decrypt(string toDecrypt, string strKey, bool base64 = true)
        {
            try
            {
                if (strKey.Length > 16)
                    strKey = strKey.Substring(0, 16);
                byte[] tmp = Encoding.Default.GetBytes(strKey);
                byte[] keyArray = new byte[16];
                tmp.CopyTo(keyArray, 0);
                byte[] toEncryptArray = base64 ? Convert.FromBase64String(toDecrypt) : StrToBin(toDecrypt);

                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.Zeros;

                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Encoding.Default.GetString(resultArray);
            }
            catch { }
            return "";
        }
        #endregion AES

        /// <summary>
        /// /// 生成验证图片
        /// /// </summary>
        /// /// <param name="checkCode">验证字符</param>
        public static void CreateImages(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 15);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 30);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.LightCyan);
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan, Color.Purple };
            Color[] c1 = { Color.LightGray, Color.LightGreen, Color.LightPink, Color.LightSkyBlue, Color.LightSteelBlue, Color.LightSalmon, Color.LightGray, Color.LightSalmon };
            //定义字体 
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体", "Comic Sans MS" };
            Random rand = new Random();
            //随机输出噪点
            for (int i = 0; i < 550; i++)
            {
                int c1index = rand.Next(7);
                int x = rand.Next(image.Width);
                int y = rand.Next(image.Height);
                g.DrawPie(new Pen(c1[c1index], 0), x, y, 6, 6, 1, 1);
            }

            //输出不同字体和颜色的验证码字符
            for (int i = 0; i < checkCode.Length; i++)
            {
                int cindex = rand.Next(6);
                int findex = rand.Next(6);
                Font fs_font = new System.Drawing.Font(font[findex], 14);
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                int ii = 4;
                if ((i + 1) % 2 == 0)
                {
                    ii = 2;
                }
                g.DrawString(checkCode.Substring(i, 1), fs_font, b, 3 + (i * 12), ii);
            }

            //画一个边框
            g.DrawRectangle(new Pen(Color.Red, 0), 100, 0, image.Width - 1, image.Height - 1);
            //输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            HttpContext.Current.Response.ClearContent();//Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/Jpeg";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
    }
}
